//
//  ZLLoginViewController.m
//  ZLExamination
//
//  Created by Zheng on 2017/8/9.
//  Copyright © 2017年 Zheng. All rights reserved.
//

#import "ZLLoginViewController.h"
#import "DYLimitLengthTextField.h"
#import "Parameters.h"
#import "UIViewExt.h"
#import "ZLTabBarController.h"
#import <IQUIView+Hierarchy.h>

#import "ZLAdministratorNavigationController.h"

@interface ZLLoginViewController ()<UITextFieldDelegate>
/** 图标*/
@property (nonatomic,strong) UIImageView* AppImageView;
/** 读书证输入框*/
@property (nonatomic, strong) DYLimitLengthTextField *cardTextField;
/** 密码输入框*/
@property (nonatomic,strong) DYLimitLengthTextField* passwordTextField;
/** 细线1*/
@property (nonatomic,strong) UIView* grayViewOne;
/** 细线2*/
@property (nonatomic,strong) UIView* grayViewTwo;
/** 登录按钮*/
@property (nonatomic, strong) UIButton *loginButton;

@property (nonatomic, strong) UIButton *adminBtn;

@property (nonatomic) BOOL isAdmin;

@end

@implementation ZLLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.AppImageView];
    [self.view addSubview:self.cardTextField];
    [self.view addSubview:self.passwordTextField];
    [self.view addSubview:self.loginButton];
    [self.view addSubview:self.grayViewOne];
    [self.view addSubview:self.grayViewTwo];
    [self.view addSubview:self.adminBtn];
    
    [_AppImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.width.equalTo(@100);
        make.height.equalTo(@100);
        make.top.equalTo(self.view.mas_top).offset(70);
    }];
    [_cardTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(15);
        make.right.equalTo(self.view.mas_right).offset(- 15);
        make.top.equalTo(self.view.mas_top).offset(200);
        make.height.equalTo(@(50));
    }];
    [_passwordTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(15);
        make.right.equalTo(self.view.mas_right).offset(- 15);
        make.top.equalTo(_cardTextField.mas_bottom).offset(10);
        make.height.equalTo(@(50));
    }];
    [_loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(15);
        make.right.equalTo(self.view.mas_right).offset(- 15);
        make.height.equalTo(@(50));
        make.top.equalTo(_cardTextField.mas_bottom).offset(70);
    }];
    
    [_adminBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_cardTextField.mas_bottom).offset(20);
        make.height.mas_equalTo(30);
        make.left.mas_equalTo(25);
    }];
    
    [_grayViewOne mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(50);
        make.right.equalTo(self.view.mas_right).offset(- 20);
        make.top.equalTo(self.cardTextField.mas_bottom).offset(- 1);
        make.height.equalTo(@1);
    }];
    [_grayViewTwo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(50);
        make.right.equalTo(self.view.mas_right).offset(- 20);
        make.top.equalTo(self.passwordTextField.mas_bottom).offset(- 1);
        make.height.equalTo(@1);
    }];
    
    _isAdmin = NO;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setStatusBarBackgroundColor:[UIColor whiteColor]];
    
    _cardTextField.text = nil;
    _passwordTextField.text = nil;
    
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [self setStatusBarBackgroundColor:kMY_BLUE_COLOR];
}

- (void)setStatusBarBackgroundColor:(UIColor *)color {
    
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
        statusBar.backgroundColor = color;
    }
}

#pragma mark - 事件点击

- (void)adminBtnAction:(UIButton *)sender {
    
    sender.selected = !sender.selected;
    _isAdmin = !_isAdmin;
    _passwordTextField.text = nil;
    _cardTextField.text = nil;

    [ZLInfoManager sharedManager].isAdminLogin = _isAdmin;
    
    if (sender.selected) {
        _cardTextField.placeholder = @" 请输入管理员账号";
        _passwordTextField.placeholder = @" 请输入密码";
        _passwordTextField.hidden = NO;
        _passwordTextField.secureTextEntry = YES;
        _grayViewTwo.hidden = NO;

        [_loginButton mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view.mas_left).offset(15);
            make.right.equalTo(self.view.mas_right).offset(- 15);
            make.height.equalTo(@(50));
            make.top.equalTo(_passwordTextField.mas_bottom).offset(70);
        }];
        
        [_adminBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_passwordTextField.mas_bottom).offset(20);
            make.height.mas_equalTo(30);
            make.left.mas_equalTo(25);
        }];
    } else {
        _cardTextField.placeholder = @" 请输入身份证号";
        _passwordTextField.hidden = YES;
        _grayViewTwo.hidden = YES;

        [_loginButton mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view.mas_left).offset(15);
            make.right.equalTo(self.view.mas_right).offset(- 15);
            make.height.equalTo(@(50));
            make.top.equalTo(_cardTextField.mas_bottom).offset(70);
        }];
        
        [_adminBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_cardTextField.mas_bottom).offset(20);
            make.height.mas_equalTo(30);
            make.left.mas_equalTo(25);
        }];
    }
}

- (void)completeButtonAction: (UIButton *)sender
{
    
    
    if ([_cardTextField.text length] == 0) return;
    
    if (_isAdmin) {
        if ([_passwordTextField.text length] == 0) return;
        //管理员
        NSString *username = _cardTextField.text;
        NSString *password = _passwordTextField.text;
        NSNumber *code = @1;
        
        NSDictionary *param = @{@"username":username,
                                @"password":password,
                                @"code":code};

        sender.userInteractionEnabled = NO;
        
        [[YCRequestDataService sharedManager] Post:@"user/user/login" parameters:param success:^(id response) {
            sender.userInteractionEnabled = YES;
            if (response[@"error_code"]) {
                NSLog(@"%@", response[@"error_msg"]);
            } else {
                //保存token
                NSString *token = response[@"response_data"][@"lists"][@"access_token"];
                [[ZLInfoManager sharedManager] setAdminAccessToken:token];

                //管理员页面
                ZLAdministratorNavigationController *nav = [[ZLAdministratorNavigationController alloc] init];
                [self presentViewController:nav animated:YES completion:nil];
            }
        } failure:^{
            NSLog(@"网络或服务器出错");
            sender.userInteractionEnabled = YES;
        }];
    } else {
        sender.userInteractionEnabled = NO;
        //学员
        NSDictionary *param = @{@"idcode":_cardTextField.text};

        [[YCRequestDataService sharedManager] Post:@"user/user/student_login" parameters:param success:^(id response) {
            sender.userInteractionEnabled = YES;
            if (response[@"error_code"]) {
                NSLog(@"%@", response[@"error_msg"]);
            } else {
                //保存token
                NSString *token = response[@"response_data"][@"lists"][@"access_token"];
                [[ZLInfoManager sharedManager] setStudentAccessToken:token];
                
                ZLTabBarController *mainVC = [[ZLTabBarController alloc] init];
                [UIApplication sharedApplication].keyWindow.rootViewController = mainVC;
            }
        } failure:^{
            NSLog(@"网络或服务器出错");
            sender.userInteractionEnabled = YES;
        }];        
    }
}

#pragma mark - 布局
- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];

}

#pragma mark - lazy load

- (UIButton *)adminBtn {
    if (!_adminBtn) {
        _adminBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_adminBtn setTitle:@" 管理员登录" forState:UIControlStateNormal];
        _adminBtn.titleLabel.font = kMyFont(12);
        [_adminBtn setImage:kIMAGE(@"login_n") forState:UIControlStateNormal];
        [_adminBtn setImage:kIMAGE(@"login_s") forState:UIControlStateSelected];
        [_adminBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [_adminBtn setTitleColor:[UIColor grayColor] forState:UIControlStateSelected];
        [_adminBtn addTarget:self action:@selector(adminBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _adminBtn;
}



- (DYLimitLengthTextField *)cardTextField
{
    if (!_cardTextField) {
        _cardTextField = [[DYLimitLengthTextField alloc] init];
        _cardTextField.backgroundColor = [UIColor clearColor];
        _cardTextField.delegate = self;
        _cardTextField.placeholder = @" 请输入身份证号";
        UIImageView *leftIcon = [[UIImageView alloc] init];
        leftIcon.image = [UIImage imageNamed:@"login_i"];
        leftIcon.width = 40;
        leftIcon.height = 30;
        leftIcon.contentMode = UIViewContentModeCenter;
        _cardTextField.leftView = leftIcon;
        _cardTextField.leftViewMode = UITextFieldViewModeAlways;
        _cardTextField.font = [UIFont systemFontOfSize:17];
        _cardTextField.borderStyle = UITextBorderStyleNone;
        _cardTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        [_cardTextField becomeFirstResponder];
        _cardTextField.limitLength = 20;
        _cardTextField.layer.cornerRadius = 5;
        [_cardTextField addTarget:self action:@selector(textDidChange:) forControlEvents:UIControlEventEditingChanged];
    }
    return _cardTextField;
}


- (void)textDidChange:(UITextField *)textField {
    
    if (_isAdmin) {
        _loginButton.backgroundColor = (_cardTextField.hasText && _passwordTextField.hasText)? kMY_BLUE_COLOR: RGB(139, 205, 245, 1.0);
    } else {
        _loginButton.backgroundColor = textField.hasText? kMY_BLUE_COLOR: RGB(139, 205, 245, 1.0);
    }
}


- (DYLimitLengthTextField *)passwordTextField
{
    if (!_passwordTextField) {
        _passwordTextField = [[DYLimitLengthTextField alloc] init];
        _passwordTextField.backgroundColor = [UIColor clearColor];
        _passwordTextField.delegate = self;
        _passwordTextField.placeholder = @" 请输入姓名";
        UIImageView *leftIcon = [[UIImageView alloc] init];
        leftIcon.image = [UIImage imageNamed:@"login_u"];
        leftIcon.width = 40;
        leftIcon.height = 30;
        leftIcon.contentMode = UIViewContentModeCenter;
        _passwordTextField.leftView = leftIcon;
        _passwordTextField.leftViewMode = UITextFieldViewModeAlways;
        _passwordTextField.font = [UIFont systemFontOfSize:17];
        _passwordTextField.borderStyle = UITextBorderStyleNone;
        _passwordTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        [_passwordTextField becomeFirstResponder];
        _passwordTextField.limitLength = 20;
        _passwordTextField.layer.cornerRadius = 5;
        _passwordTextField.hidden = YES;
        [_passwordTextField addTarget:self action:@selector(textDidChange:) forControlEvents:UIControlEventEditingChanged];
    }
    return _passwordTextField;
}
- (UIButton *)loginButton {
    if (!_loginButton) {
        _loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _loginButton.backgroundColor = RGB(139, 205, 245, 1.0);
        _loginButton.layer.cornerRadius = 5;
        [_loginButton setTitle:@"登录" forState:UIControlStateNormal];
        [_loginButton addTarget:self action:@selector(completeButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loginButton;
}
- (UIView *)grayViewOne
{
    if (!_grayViewOne) {
        _grayViewOne = [[UIView alloc] init];
        _grayViewOne.backgroundColor = [UIColor grayColor];
        
    }
    return _grayViewOne;
}
- (UIView *)grayViewTwo
{
    if (!_grayViewTwo) {
        _grayViewTwo = [[UIView alloc] init];
        _grayViewTwo.backgroundColor = [UIColor grayColor];
        _grayViewTwo.hidden = YES;
    }
    return _grayViewTwo;
}
- (UIImageView *)AppImageView
{
    if (!_AppImageView) {
        _AppImageView = [[UIImageView alloc] init];
        _AppImageView.image = [UIImage imageNamed:@"loginIcon"];
    }
    return _AppImageView;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
